#define _CRT_SECURE_NO_WARNINGS 1

#include <vector>
using namespace std;

class Solution {
    bool check[301][301] = { 0 };
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int m;
    int n;
public:
    void dfs(vector<vector<char>>& grid, int r, int c)
    {
        for (int i = 0; i < 4; ++i)
        {
            check[r][c] = true;
            int x = r + dx[i], y = c + dy[i];
            if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' && check[x][y] == false)
            {
                dfs(grid, x, y);
            }
        }
    }

    int numIslands(vector<vector<char>>& grid) {
        m = grid.size();
        n = grid[0].size();
        int ret = 0;
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (grid[i][j] == '1' && check[i][j] == false)
                {
                    dfs(grid, i, j);
                    ++ret;
                }
            }
        }
        return ret;
    }
};